<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Demand;
use App\Models\Areas;
use App\Models\BidLists;
use App\Models\Buys;
use App\Models\Categorys;
use App\Models\rewardTypes;

use App\Models\CompanyInfos;
use App\Models\Demands;
use App\Models\Mails;
use App\Models\Messages;
use App\Models\Stores;
use App\Models\Users;
use App\Models\rewardOrder;
use Illuminate\Http\Request;

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\DemandExport;

class DemandController extends Controller {

    /**
     * 页面
     * @return view
     */
    public function index(){
        
        //获取分类
        $categorys = Categorys::getCascaderList();
        $categorys = json_encode($categorys);
 		
        //获取全部分类
        $types = rewardTypes::getCascaderList();
        $types = json_encode($types);
   	
        return view('admin.demand.index',compact('categorys','types'));
    }

    /**
     * 列表数据
     * @param Request $request
     * @return bool
     */
    public function list(Request $request){
        try{
            $params = [
                'kwd' => (string)$request->get('kwd',''),
                'status' => (int)$request->get('status',0),
            	'r_status' => (int)$request->get('r_status',0),
            		
                'bid' => (int)$request->get('bid',0),
                'cid' => (int)$request->get('cid',0),
            	'tid' => (int)$request->get('tid',0),
            		
                'start' => (string)$request->get('start',''),
                'end' => (string)$request->get('end',''),
                'sort' => (string)$request->get('sort',''),
            ];
            $lists = Demands::getList($params);
            foreach($lists as $k=>$v){
            	$times = rewardOrder::where("reward_id",$v['id'])->count("id");
            	if($times>0){
            		$lists[$k]['r_rate'] = $v['ownnumber']/$times*100;
            	}else{
            		$lists[$k]['r_rate'] = "暂无报名";
            	}
            	
            }
          
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 编辑
     * @param Request $request
     * @return bool|view
     */
    public function edit(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $info = [];
            if($id){
                $info = Demands::findOrFail($id);
                $info['cate_id'] = [$info['cate_pid'],$info['cate_id']];
                $info['area'] = [$info['area']];
                $info['pttype_id'] = [$info['pttype_id']];
            }
            $info = json_encode($info);

            //获取分类
            $category = Categorys::getCascaderList();
            $categorys = json_encode($category);
            //获取区域
            $area = Areas::getCascaderList();
            $areas = json_encode($area);
            //获取全部分类
            $types = rewardTypes::getCascaderList();
            $types = json_encode($types);

            return view('admin.demand.demand_update',compact('info','id','categorys','areas','types'));
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 更新1
     * @param Demand $request
     * @return bool
     */
    public function update(Demand $request){
        try{
            $data = $request->all();
            
     
            $data['pttype_id'] = $data['pttype_id'][0];
            $data['cate_pid'] = $data['cate_id'][0];
            
            $cate_id = 0;
            if (isset($data['cate_id'][1])){
                $cate_id = $data['cate_id'][1];
            }
            $data['cate_id'] = $cate_id;
            $data['user_name'] = '平台';
             
            $data['area'] = $data['area'][0];
           
            
            if($data['id']){
                $info = Demands::findOrFail($data['id']);
                $info->update($data);
                return $this->writeJson(0,null,'修改信息成功');
            }else{
                unset($data['id']);
                Demands::create($data);
                return $this->writeJson(0,null,'新增信息成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 拒绝
     * @param Request $request
     * @return bool
     */
    public function lock(Request $request){
        try{
            $id = (int)$request->get('id',0);
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = Demands::findOrFail($id);
            $info->update(['status' => Demands::STATUS_2]);
            //发送站内信
            if($info['user_id'] != null){
                $template = [
                    'title' => '需求审核通知',
                    'content' => '您发布的任务"' . $info['title'] .'"审核被驳回!请到 个人中心-需求管理中心 查看详情,修改后可以再次申请。',
                    'user_id' => $info['user_id'],
                    'status' => 1,
                    'type' => 1,
                ];
                Mails::create($template);
            }
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    public function setrcommend(Request $request){
    	try{
    		$id = (int)$request->get('id');
    		if(empty($id)){
    			return $this->writeJson(1,null,'参数错误');
    		}
    		$is_rc = (int)$request->get('is_rc',0);
    	
    		$info = Demands::findOrFail($id);
    		$info->update(['is_recommend' => $is_rc]);
    
    		return $this->writeJson(0);
    	}catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }
    
    /**
     * 通过
     * @param Request $request
     * @return bool
     */
    public function active(Request $request){
        try{
            $id = (int)$request->get('id',0);
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = Demands::findOrFail($id);
            $info->update(['status' => Demands::STATUS_3]);
            //发送站内信
            if($info['user_id'] != null){
                $template = [
                    'title' => '需求审核通知',
                    'content' => '您发布的任务："' . $info['title'] .'"审核通过!请到 个人中心-需求管理中心 查看详情',
                    'user_id' => $info['user_id'],
                    'status' => 1,
                    'type' => 1,
                ];
                Mails::create($template);
            }
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 单个/多个删除
     * @param Request $request
     * @return bool
     */
    public function destroy(Request $request){
        try{
            $id = $request->get('id');
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            if(is_array($id)){
                $where['id'] = ['in',$id];
            }else{
                $where['id'] = $id;
            }
            //修改软删除 19-7-31
            $data['status'] = -1;
            Demands::where($where)->update($data);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 投标供应商列表数据
     * @param Request $request
     * @return bool
     */
    public function user_list(Request $request)
    {
        try {
            $params = [
                'kwd' => (string)$request->get('kwd', ''),
                'type' => (int)$request->get('type', 2),
                'status' => (int)$request->get('status', 1),
                'id' =>  (array)$request->get('ids', 0),
            ];
            $lists = Users::getList($params);
            return $this->writeJson(0, $lists);
        } catch (\Exception $e) {
            return $this->writeJson(1, null, $e->getMessage());
        }
    }

    /**
     * 指定投标供应商
     * @param Demand $request
     * @return bool
     */
    public function store_update(Request $request)
    {
        try{
            $data = $request->all();
            $info = Demands::findOrFail($data['id']);
            $data['bid'] = 2;
            $now = date('Y-m-d H:i:s');
            if($data['way'] == 1){

            }elseif ($data['way'] == 2){
                $insert = [];
                $mails = [];
                foreach ($data['bid_id'] as $k=>$v){
                    $store_name = Stores::where('user_id',$v)->value('seller_name');
                    $bid = BidLists::where(['store_id'=>$v,'demand_id'=>$data['id']])->value('store_id');
                    if(!empty($bid)){
                        return $this->writeJson(1,null,$store_name . '供应商已经投标该需求,请重新选择');
                    }
                    $map = [
                        'bid_sn' => Buys::makePaySn($v),
                        'demand_id' => $data['id'],
                        'user_id' => $info['user_id'],
                        'user_name' => $info['user_name'],
                        'store_id' => $v,
                        'store_name' => $store_name,
                        'bid_time' => $now,
                        'bid_fee' => $info['service_charge'],
                        'order_from' => 2,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                    array_push($insert, $map);
                    //发送站内信-需求订单匹配通知
                    $template = [
                        'title' => '需求订单匹配通知',
                        'content' => '我们已于您提前联系达成接收意向,并扣除您'.$info['bid_costs'].'的投标费用，请及时前往"竞标管理中心"获取雇主联系方式，与雇主联系后进行下一步合作；',
                        'user_id' => $v,
                        'status' => 1,
                        'type' => 1,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                    array_push($mails, $template);
                }
                BidLists::insert($insert);
                Users::where('id',$v)->decrement('balance',$info['bid_costs']);//扣除投标费用
                Demands::where('id',$data['id'])->increment('number', sizeof($data['bid_id']));//增加投标数量
                Mails::insert($mails);
            }elseif ($data['way'] == 3){
                $store_name = Stores::where('user_id',$data['bid_id'])->value('seller_name');
                $bid = BidLists::where(['store_id'=>$data['bid_id'],'demand_id'=>$data['id']])->value('store_id');
                if(!empty($bid)){
                    return $this->writeJson(1,null,$store_name . '供应商已经投标该需求,请重新选择');
                }
                $map = [
                    'bid_sn' => Buys::makePaySn($data['bid_id']),
                    'demand_id' => $data['id'],
                    'user_id' => $info['user_id'],
                    'user_name' => $info['user_name'],
                    'store_id' => $data['bid_id'],
                    'store_name' => $store_name,
                    'bid_time' => $now,
                    'bid_fee' => $info['service_charge'],
                    'bid_status' => 2,
                    'finnshed_time' => $now,
                    'order_from' => 2,
                ];
                $result = BidLists::create($map);
                //修改其他投标供应商为：未中标
                $list = BidLists::where('demand_id',$data['id'])->where('id','<>',$result['id'])->get(['id']);
                if(empty($list)){
                    foreach ($list as $val){
                        $update = [
                            'bid_status' => 1,
                            'finnshed_time' => date('Y-m-d H:i:s'),
                        ];
                        BidLists::where('id',$val['id'])->Update($update);
                    }
                }
                Users::where('id',$data['bid_id'])->decrement('balance',$info['bid_costs']);//扣除投标费用
                Demands::where('id',$data['id'])->increment('number',1);//增加投标数量
                $data['bid'] = 3;
                //发送站内信-需求订单中标通知
                $mails = [
                    'title' => '需求订单匹配通知',
                    'content' => '经平台回访核实，您于' . $map['bid_time'] . '投标了需求"' . $info['title'] .'",并与' . $info['user_name'] .'达成合作并签订了合同,平台已扣除此需求的投标费用'.$info['bid_costs'].'元，请及时前往"竞标管理中心"上传合同，谢谢合作。',
                    'user_id' => $data['bid_id'],
                    'status' => 1,
                    'type' => 1,
                ];
                Mails::create($mails);
                //发送系统消息
                $message = [
                    'title' => '恭喜' . $store_name . '成功中标' . $info['title'],
                    'content' => '恭喜' . $store_name . '成功中标' . $info['title'],
                    'type' =>5,
                ];
                Messages::create($message);
            }
            //改变需求状态
            unset($data['id']); unset($data['bid_id']); unset($data['bid_count']);
            $info->update($data);
            return $this->writeJson(0,null,'配送成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    
    /**
     * Excel导出
     * @param Request $request
     * @return bool
     */
    public function exports(Request $request){
    	$ids = $request->get('ids'); 
    	$export = new DemandExport($ids);
    	//这里可以传参到服务层
    	return Excel::download($export, '任务列表.xlsx');
    }

}
